/*
    The definition of the angel and the distance of moving.
*/
const UP = 1, LEFT = 2, RIGHT = 0, DOWN = 3;
const DIST = 45;

/*
    Add the artist.    
*/
function draw() {
    var xmlns = "http://www.w3.org/2000/svg";
    var svg = document.getElementById('svgMaze');

    var artist = document.createElementNS(xmlns, 'clipPath');
    artist.setAttribute('id', 'artistPath');
    var clipRect = document.createElementNS(xmlns, 'rect');
    clipRect.setAttribute('id', 'clipRect');
    clipRect.setAttribute('width', 50);
    clipRect.setAttribute('height', 50);
    clipRect.setAttribute('x',45);
    clipRect.setAttribute('y',95);
    artist.appendChild(clipRect);
    svg.appendChild(artist);

    var artistImage = document.createElementNS(xmlns, 'image');
    artistImage.setAttribute('id','artist');
    artistImage.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href',
                    './res11/artist.png');
    artistImage.setAttribute('height', 50);
    artistImage.setAttribute('width', 50);
    artistImage.setAttribute('x', 45);
    artistImage.setAttribute('y', 95);
    artistImage.setAttribute('clip-path', 'url(#artistPath)');
    svg.appendChild(artistImage);
}

draw();

var t1 = new TimelineLite();
var win = false;
// var Dire_First = false;
// var Dire_Second = false;

function move(angle, pixels) {
    let artist = document.getElementById("artist");
    let moveX = pixels * Math.cos(angle * Math.PI / 2);
    let moveY = pixels * Math.sin(angle * Math.PI / 2);
    console.log(moveX);
    console.log(moveY);
    t1.add(TweenLite.to(artist, 1, {x : "+= " + moveX, y : "-= " + moveY}));
}

function moveLeft() {
    move(LEFT, DIST);
}

function moveRight() {
    move(RIGHT, DIST);
    var path = document.getElementById("3");
    t1.add(TweenLite.to(path, 0, {css:{stroke:"black"}}));
    win = true;
}

function moveUp() {
    move(UP, DIST);
    var path = document.getElementById("4");
    t1.add(TweenLite.to(path, 0, {css:{stroke:"black"}}));
}

function moveDown() {
    move(DOWN, DIST);
}

function runButtonClick() {
    var code = Blockly.JavaScript.workspaceToCode(workspace);
        console.log(code);
        Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
        try {
                alert(code);
                eval(code);
                setTimeout(check_win, 4000);
        } catch (e) {
                alert(e);
        }
}

function check_win(){
    if(win){
        var t = confirm("恭喜你通过本关，是否进行下一关？");
        if(t){
            window.location.href="course1-11/course1-11-2.html";
        }
    }
    else{
        document.getElementById("hint").innerHTML = "继续编码！有些地方还不完全正确。";
    }
}